package me.zhengjie.modules.finace_taxation.rest;

import com.alibaba.fastjson.JSONObject;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.finace_taxation.domain.FtUsers;
import me.zhengjie.modules.finace_taxation.service.FtUsersService;
import me.zhengjie.modules.finace_taxation.service.dto.FtUsersDto;
import me.zhengjie.modules.finace_taxation.service.dto.FtUsersQueryParam;
import me.zhengjie.utils.RedisUtils;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
* @author 杨荣森
* @date 2021-06-28
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "FtUser管理")
@RequestMapping("/api/ft/ftUsers")
public class FtUsersController {

    private final FtUsersService ftUsersService;
    private final PasswordEncoder passwordEncoder;
    private final RedisUtils redisUtils;

    @GetMapping
    @Log("查询用户")
    @ApiOperation("查询用户")
//    @PreAuthorize("@el.check('ftUsers:list')")
    public ResponseEntity query(FtUsersQueryParam query, Pageable pageable){
        return new ResponseEntity<>(ftUsersService.queryAll(query,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增用户")
    @ApiOperation("新增用户")
//    @PreAuthorize("@el.check('ftUsers:add')")
    public ResponseEntity create(@Validated @RequestBody FtUsersDto ftUsers){
        // 默认密码 123456
//        ftUsers.setPassword(passwordEncoder.encode("123456"));
        ftUsers.setPassword("123456");
        ftUsers.setNickName(ftUsers.getPhoneNumber());
        return new ResponseEntity<>(ftUsersService.insert(ftUsers),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改用户")
    @ApiOperation("修改用户")
//    @PreAuthorize("@el.check('ftUsers:edit')")
    public JSONObject update(@Validated @RequestBody FtUsersDto resources){
        JSONObject resObj = new JSONObject();
        int i = ftUsersService.updateById(resources);
        if (i > 0) {
            resObj.put("message", "修改成功");
            resObj.put("code", 200);
            resObj.put("success", true);
            return resObj;
        }
        resObj.put("message", "修改失败");
        resObj.put("code", 500);
        resObj.put("success", false);
        return resObj;
    }

    @DeleteMapping
    @Log("删除用户")
    @ApiOperation("删除用户")
//    @PreAuthorize("@el.check('ftUsers:del')")
    public ResponseEntity delete(@RequestBody Set<String> ids) {
        ftUsersService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/updateAvatar")
    @Log("修改头像")
    @ApiOperation("修改头像")
    public JSONObject updateAvatar(@RequestBody FtUsers ftUsers) {
        JSONObject resObj = new JSONObject();
        int i = ftUsersService.updateAvatar(ftUsers);
        if (i > 0) {
            resObj.put("message", "修改成功");
            resObj.put("code", 200);
            resObj.put("success", true);
        } else {
            resObj.put("message", "修改失败");
            resObj.put("code", 500);
            resObj.put("success", false);
        }
        return resObj;

    }

    @PostMapping("/WXLogin")
    @Log("微信登录")
    @ApiOperation("微信登录")
    public JSONObject QQLogin(@RequestBody FtUsersDto ftUsersDto) {
        return ftUsersService.WXLogin(ftUsersDto);
    }


    // 验证旧手机号的验证码是否正确
    @GetMapping("/verifyCaptcha")
    @Log("验证旧手机号的验证码是否正确")
    @ApiOperation("验证旧手机号的验证码是否正确")
    public JSONObject verifyCaptcha(@RequestBody JSONObject jsonObject) {
        JSONObject resObj = new JSONObject();
        String code = jsonObject.getString("code");
        String phone = jsonObject.getString("phone");
        String captcha = (String) redisUtils.get(phone);

        if (!code.equals(captcha)) {
            // 如果缓存中的验证码和用户输入的验证码不一致,则return
            resObj.put("message", "验证码错误,请重新输入! ");
            resObj.put("code", 500);
            resObj.put("success", false);
            return resObj;
        }

        resObj.put("message", "验证码正确! ");
        resObj.put("code", 200);
        resObj.put("success", true);
        return resObj;
    }


    // 修改新的手机号
    @PostMapping("/updatePhone")
    @Log("修改手机号")
    @ApiOperation("修改手机号")
    public JSONObject updatePhone(@RequestBody JSONObject jsonObject) {
        JSONObject resObj = new JSONObject();
        String userId = jsonObject.getString("userId");
//        String code = jsonObject.getString("code");
        String phone = jsonObject.getString("phone");
//        String captcha = (String) redisUtils.get(phone);
//        redisUtils.del(phone); // 清除缓存中的验证码

//        if (!code.equals(captcha)) {
//            // 如果缓存中的验证码和用户输入的验证码不一致,则return
//            resObj.put("message", "验证码错误,请重新输入! ");
//            resObj.put("code", 500);
//            resObj.put("success", false);
//            return resObj;
//        }

//        // 判断该手机号是否已注册,查数据库
        FtUsers userByPhone = ftUsersService.findByPhone(phone);
        if (userByPhone != null) {
            // 该手机号已被注册,请重新输入
            resObj.put("message", "该手机号已被注册,请重新输入! ");
            resObj.put("code", 500);
            resObj.put("success", false);
            return resObj;
        }

        FtUsers ftUsers = ftUsersService.getById(userId);
        ftUsers.setPhoneNumber(phone);
        int flag = ftUsersService.updateByPhone(ftUsers);
        if (flag > 0) {
            resObj.put("message", "更新成功! ");
            resObj.put("code", 200);
            resObj.put("success", true);
            return resObj;
        }

        resObj.put("message", "更新失败! ");
        resObj.put("code", 500);
        resObj.put("success", false);
        return resObj;
    }

    // 修改密码
    @PostMapping("/updatePwd")
    @Log("修改密码")
    @ApiOperation("修改密码")
    public JSONObject updatePwd(@RequestBody FtUsers ftUsers) {
        JSONObject resObj = new JSONObject();
        int i = ftUsersService.updatePwd(ftUsers);
        if (i > 0) {
            resObj.put("message", "修改成功");
            resObj.put("code", 200);
            resObj.put("success", true);
            return resObj;
        }
        resObj.put("message", "修改失败");
        resObj.put("code", 500);
        resObj.put("success", false);
        return resObj;
    }


    @Log("导出用户")
    @ApiOperation("导出用户")
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response, FtUsersQueryParam query) throws IOException {
        ftUsersService.download(ftUsersService.queryAll(query), response);
    }

}
